package vip.xiaonuo.smzq.modular.kcl.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.catalina.connector.Request;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.smzq.core.tools.file.PathUtils;
import vip.xiaonuo.smzq.modular.deom.NumEntity;
import vip.xiaonuo.smzq.modular.dictionary.entity.Cb01Zh;
import vip.xiaonuo.smzq.modular.dictionary.mapper.Cb01ZhMapper;
import vip.xiaonuo.smzq.modular.kcl.entity.Wjglb;
import vip.xiaonuo.smzq.modular.kcl.entity.Zlsc;
import vip.xiaonuo.smzq.modular.kcl.entity.vo.FileUpload;
import vip.xiaonuo.smzq.modular.kcl.entity.vo.Zlxqcx;
import vip.xiaonuo.smzq.modular.kcl.mapper.WjglbMapper;
import vip.xiaonuo.smzq.modular.kcl.mapper.ZlscMapper;
import vip.xiaonuo.smzq.modular.kcl.service.IZlscService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.smzq.modular.lifecycle.service.module.LifeCycleHanderDataService;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 资料上传 服务实现类
 *
 * @author sqq
 * @since 2024-03-13
 */
@Service
public class ZlscServiceImpl extends ServiceImpl<ZlscMapper, Zlsc> implements IZlscService {

    @Resource
    private ZlscMapper zlscMapper;

    @Resource
    private WjglbMapper wjglbMapper;//文件上传关联

    @Resource
    private Cb01ZhMapper cb01ZhMapper;//字典综合1
    @Autowired
    protected HttpServletResponse response;

    @Autowired
    LifeCycleHanderDataService lifeCycleHanderDataService;
    @Value("${file.base}")
    String baseFilePath;
    @Override
    public Page<Zlsc> page(Zlsc zlsc) {
        QueryWrapper<Zlsc> queryWrapper = new QueryWrapper<>();
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Override
    public int addList(List<FileUpload> fileUploadList, String kqbh, Integer djflbm, Integer nd) {
        return 0;
    }

    /**
     * 文件上传
     *
     * @param files 文件
     * @param zlsc  文件上传实体
     * @return 文件上传编码
     */
    @Override
    public List<Zlxqcx> fileUpload(List<MultipartFile> files, Zlsc zlsc) {
        List<Zlxqcx> zlxqcxList = new ArrayList<>();
        //设置文件清单主键id
        String uuid = UUID.randomUUID().toString();
        zlsc.setPkid(uuid);
       // zlsc.setZlsj(DateUtil.format(new Date(), "YYYYMMdd"));
        int count = zlscMapper.insert(zlsc);
        if (count > 0) {
            List<String> ids=new ArrayList<>();
            int sequence = 1;
            QueryWrapper<Zlsc> zlscQuery = new QueryWrapper<>();
            zlscQuery.select("pkid");
            zlscQuery.eq("djflbh", zlsc.getDjflbh()).eq("kqbh", zlsc.getKqbh()).eq("nd", zlsc.getNd())
                    .eq("zlxz", zlsc.getZlxz()).eq("kyqdjlx", zlsc.getKyqdjlx()).eq("jdlx", zlsc.getJdlx()).eq("kyqklx", zlsc.getKyqklx())
                    .eq("zlsj", zlsc.getZlsj());
            List<Zlsc> zlscList = zlscMapper.selectList(zlscQuery);
            if (zlscList!=null&&zlscList.size() > 0){
             ids=zlscList.stream().map(Zlsc::getPkid).collect(Collectors.toList());
            }

            for (MultipartFile file : files) {

                //文件名称

                String fileName = file.getOriginalFilename();
                File file1 = new File(baseFilePath+ File.separator  + fileName);
//                File file1 = new File(PathUtils.getUpLoadPath(baseFilePath) + File.separator  + fileName);
                try {
                    FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                fileName = URLDecoder.decode(fileName, StandardCharsets.UTF_8);//解码
                String suffix = fileName.substring(fileName.lastIndexOf("."));
                String wjName = fileName.substring(0, fileName.lastIndexOf("."));
                //设置文件清单主键id
                String uuidfile = UUID.randomUUID().toString();

                QueryWrapper<Cb01Zh> Cb01Zh1 = new QueryWrapper<>();
                Cb01Zh1.eq("dm", zlsc.getKyqklx());
                Cb01Zh kyqklx = cb01ZhMapper.selectOne(Cb01Zh1);
                QueryWrapper<Cb01Zh> Cb01Zh2 = new QueryWrapper<>();
                Cb01Zh2.eq("dm", zlsc.getKyqdjlx());
                Cb01Zh kyqdjlx = cb01ZhMapper.selectOne(Cb01Zh2);
                QueryWrapper<Cb01Zh> Cb01Zh3 = new QueryWrapper<>();
                Cb01Zh3.eq("dm", zlsc.getJdlx());
                Cb01Zh jdlx = cb01ZhMapper.selectOne(Cb01Zh3);


                //查询同资料性质，矿业权库类型，矿业权登记类型，资料时间，节点类型 的文件有多少，寻找缺少的断位的顺序号
                QueryWrapper<Wjglb> wjglbQuery = new QueryWrapper<>();
                wjglbQuery.in("zlsc_id",ids);
                wjglbQuery.orderByAsc("zlsxh");
                 List<Wjglb> wjglbList = wjglbMapper.selectList(wjglbQuery);
                List<Integer> zlsxhs=new ArrayList<>();
               if (wjglbList!=null&&wjglbList.size() > 0){
                   zlsxhs=wjglbList.stream().map(Wjglb::getZlsxh).collect(Collectors.toList());
               }
                Wjglb wjglb = new Wjglb();
               if (zlsxhs.size() > 0){
                   try{
                       for (int i=1;i<=(zlsxhs.get(zlsxhs.size()-1)+1);i++){
                           if (!zlsxhs.contains(i)){
                               wjglb.setZlsxh(i);
                               String zlbm = getZlbm(kyqklx.getMc(), kyqdjlx.getMc(), jdlx.getMc(), i, zlsc.getZlsj());
                               wjglb.setWjbh(zlbm);
                               break;
                           }
                       }
                   }catch (Exception e){
                       System.out.println(e);
                       return null;
                   }

               }else{
                   wjglb.setZlsxh(sequence);
                   String zlbm = getZlbm(kyqklx.getMc(), kyqdjlx.getMc(), jdlx.getMc(), sequence, zlsc.getZlsj());
                   wjglb.setWjbh(zlbm);
               }
                wjglb.setPkid(uuidfile);
                wjglb.setZlscId(uuid);
                wjglb.setWjmc(wjName);
                wjglb.setWjhz(suffix);
                wjglb.setWjdx(Math.toIntExact(file1.length()));
                wjglb.setWjlj(file1.getPath());
                wjglb.setWjsclj(file1.getPath());
                wjglb.setDjflbh(zlsc.getDjflbh());
                wjglb.setKqbh(zlsc.getKqbh());
                wjglb.setNd(zlsc.getNd());
                wjglb.setScsj(DateUtil.format(new Date(), "YYYYMMdd"));

                int fileCount = wjglbMapper.insert(wjglb);
                //如果上传成功则组织返回数据
                if (fileCount > 0) {
                    Zlxqcx zlxqcx = new Zlxqcx();
                    zlxqcx.setGuanlianId(uuid);
                    zlxqcx.setPkid(wjglb.getPkid());
                    //矿业权库类型
                    zlxqcx.setKyqklx(zlsc.getKyqklx());
                    //矿业权登记类型
                    zlxqcx.setKyqdjlx( zlsc.getKyqdjlx());
                    //节点类型
                    zlxqcx.setJdlx(zlsc.getJdlx());
                    //资料性质
                    zlxqcx.setZlxz(zlsc.getZlxz());
                    zlxqcx.setWjbh(wjglb.getWjbh());
                    zlxqcx.setWjmc(wjglb.getWjmc());
                    zlxqcx.setWjhz(wjglb.getWjhz());
                    zlxqcx.setWjlj(wjglb.getWjlj());
                    zlxqcx.setKqbh(wjglb.getKqbh());
                    zlxqcx.setDjflbh(wjglb.getDjflbh());
                    zlxqcx.setNd(wjglb.getNd());
                    zlxqcx.setZlsxh(wjglb.getZlsxh());
                    zlxqcx.setZlsj(zlsc.getZlsj());
                    zlxqcxList.add(zlxqcx);
                }

                sequence++;
            }
        }
         if (zlsc.getZlxz()==300001){
             lifeCycleHanderDataService.saveLifeCycleData(zlxqcxList);
         }

        return zlxqcxList;
    }


    //获取文件编码
    public String getZlbm(String kyqklx, String kyqdjlx, String jdlx, int count,String zlsj) {
        String zlbm = "";
        //时间戳
        String timeNum =zlsj;
        if (timeNum==null&&timeNum.length()==0){
            timeNum = DateUtil.format(new Date(), "YYYYMMdd");
        }
        List<NumEntity> nums = JSONUtil.toList(ResourceUtil.readUtf8Str("json" + File.separator + "num.json"), NumEntity.class);
        for (NumEntity num : nums) {
            if (kyqklx.equals(num.getMc())) {
                kyqklx = num.getDm();
            } else if (kyqdjlx.equals(num.getMc())) {
                kyqdjlx = num.getDm();
            } else if (jdlx.equals(num.getMc())) {
                jdlx = num.getDm();
            }
        }
        if ((count - 10) >= 0) {
            zlbm = kyqklx + kyqdjlx + timeNum + jdlx + count;
        } else {
            zlbm = kyqklx + kyqdjlx + timeNum + jdlx + "0" + count;
        }

        return zlbm;

    }

    /**
     * 文件预览
     *
     * @param filePath 文件路径
     */
    @Override
    public void fileShow(String filePath) {


        PathUtils.singleFileShow(filePath,response);


//        try {
//            filePath = java.net.URLDecoder.decode(filePath, "UTF-8");
//            File file = new File(filePath);
//            //输入流
//            InputStream fis = new FileInputStream(file);
//            String type = "";
//            switch (FileUtil.extName(filePath).toLowerCase()) {
//                case "xlsx":
//                case "xls":
//                    type = "application/vnd.ms-excel";
//                    break;
//                case "doc":
//                case "docx":
//                    type = "application/msword";
//                    break;
//                case "pdf":
//                    type = "application/pdf";
//                    break;
//                case "img ":
//                    type = "application/x-img";
//                    break;
//                case "jpeg":
//                case "jpg":
//                    type = "image/jpeg";
//                    break;
//            }
//            if (type.length() > 0) {
//                response.setContentType(type);
//            } else {
//                response.setContentType("image//" + FileUtil.extName(filePath));
//            }
//            response.setCharacterEncoding("UTF-8");
//            // 数据输出
//            OutputStream outputStream = response.getOutputStream();// 打开流
//            byte[] bytes = new byte[1024];
//            int len = 0;
//            while ((len = fis.read(bytes)) != -1) {
//                outputStream.write(bytes, 0, len);
//            }
//            // 冲刷及关闭
//            fis.close();
//            outputStream.flush();
//            outputStream.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }


}
